package com.yunhe.authority.service.base.impl;

import com.yunhe.authority.service.base.ThemeService;
import com.yunhe.common.model.PageParam;
import com.yunhe.authority.domain.base.Theme;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.authority.repository.base.ThemeRepository;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 主题Service
 * @desc 主题服务类实现
 * @author liuronglei
 */
@Service
public class ThemeServiceImpl implements ThemeService {

    @Autowired
    ThemeRepository themeRepository;

    /**
     * 主题处理和判断
     * @param theme 主题对象
     */
    private void processBeforeSave(Theme theme)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断主题编号是否为空
        if (StringUtil.isEmpty(theme.getName())
                || theme.getCode() == null
                || StringUtil.isEmpty(theme.getTitle())) {
            throw new ArgumentErrorException("主题代码、主题编号、主题标题不能为空");
        }
        //判断主题编号是否已存在
        Theme themeByName = this.findByName(theme.getName());
        if (themeByName != null) {
            if (theme.getId() == null || themeByName.getId().longValue() != theme.getId().longValue()) {
                throw new UniqueConstraintsException("该主题编号已存在");
            }
        }
        //判断主题代码是否已存在
        Theme themeByCode = this.findByCode(theme.getCode());
        if (themeByCode != null) {
            if (theme.getId() == null || themeByCode.getId().longValue() != theme.getId().longValue()) {
                throw new UniqueConstraintsException("该主题代码已存在");
            }
        }
    }

    /**
     * 新增主题
     * @param theme 新增对象
     */
    @Override
    @Transactional
    public Theme createTheme(Theme theme)
            throws ArgumentErrorException, UniqueConstraintsException {
        theme.setId(null);
        processBeforeSave(theme);
        return themeRepository.save(theme);
    }

    /**
     * 批量新增主题
     * @param list 主题列表
     */
    @Override
    @Transactional
    public Iterable<Theme> createTheme(List<Theme> list)
            throws ArgumentErrorException, UniqueConstraintsException {
        for (Theme theme : list) {
            theme.setId(null);
            processBeforeSave(theme);
        }
        return themeRepository.saveAll(list);
    }

    /**
     * 根据id删除主题
     * @param themeId id
     */
    @Override
    @Transactional
    public void deleteTheme(Long themeId) {
        themeRepository.deleteById(themeId);
    }

    /**
     * 根据主题代码删除主题
     * @param code 主题代码
     */
    @Override
    @Transactional
    public Long deleteThemeByCode(Long code) {
        return themeRepository.deleteByCode(code);
    }

    /**
     * 根据主题编号删除主题
     * @param name 主题编号
     */
    @Override
    @Transactional
    public Long deleteThemeByName(String name) {
        return themeRepository.deleteByName(name);
    }

    /**
     * 更新主题（更新全部字段）
     * @param theme 要更新的主题对象
     */
    @Override
    @Transactional
    public Theme updateTheme(Theme theme)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = theme.getId() != null && themeRepository.existsById(theme.getId());
        if (!exists) {
            throw new ObjectNotFoundException("找不到ID为" + theme.getId() + "的主题");
        }
        processBeforeSave(theme);
        return themeRepository.save(theme);
    }

    /**
     * 更新主题（更新指定字段）
     * @param themeId id
     * @param code 主题代码
     * @param name 主题编号
     * @param title 主题标题
     */
    @Override
    @Transactional
    public Theme updateTheme(Long themeId,
                             Long code,
                             String name,
                             String title)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        Theme theme = this.findByThemeId(themeId);
        if (theme == null) {
            throw new ObjectNotFoundException("找不到ID为" + themeId + "的主题");
        }
        Optional.ofNullable(code).ifPresent(theme::setCode);
        Optional.ofNullable(name).ifPresent(theme::setName);
        Optional.ofNullable(title).ifPresent(theme::setTitle);
        processBeforeSave(theme);
        return themeRepository.save(theme);
    }

    /**
     * 根据ID获得主题对象
     * @param id id
     */
    @Override
    public Theme findByThemeId(Long id) {
        return themeRepository.findById(id).orElse(null);
    }

    /**
     * 根据主题代码获得主题对象
     * @param code 主题代码
     */
    @Override
    public Theme findByCode(Long code) {
        return themeRepository.findByCode(code);
    }

    /**
     * 根据主题编号获得主题对象
     * @param name 主题编号
     */
    @Override
    public Theme findByName(String name) {
        return themeRepository.findByName(name);
    }

    /**
     * 根据主题标题获得主题对象
     * @param title 主题标题
     */
    @Override
    public Theme findByTitle(String title) {
        return themeRepository.findByTitle(title);
    }

    /**
     * 获得所有主题对象
     * @param pageParam 分页对象
     */
    @Override
    public Iterable<Theme> findThemes(PageParam pageParam) {
        Iterable<Theme> results;
        if (QueryUtil.needPaging(pageParam)) {
            results = themeRepository.findAll(QueryUtil.getPageRequest(pageParam));
        } else {
            Sort sort = pageParam == null ? null : QueryUtil.getSort(pageParam.getSort());
            if (sort != null) {
                results = themeRepository.findAll(sort);
            } else {
                results = themeRepository.findAll();
            }
        }
        return results;
    }
}
